package com.aqie.rabbit.api.exchange.direct;

import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

public class ConsumerTest {
    private static final String QUEUE_NAME = "test001";
    private static final String IP_ADDRESS = "127.0.0.1";
    private static final String VIRTUAL_HOST = "/";
    private static final String EXCHANGE_NAME = "exchange_demo";
    private static final String ROUTING_KEY = "routingkey_demo";
    private static final int PORT = 5672;

    public static void main(String[] args) throws IOException, TimeoutException, InterruptedException {
        Address[] addresses = new Address[]{
                new Address(IP_ADDRESS, PORT)
        };
        //1 创建一个ConnectionFactory, 并进行配置
        ConnectionFactory connectionFactory = new ConnectionFactory();

        connectionFactory.setVirtualHost(VIRTUAL_HOST);

        //2 通过连接工厂创建连接
        Connection connection = connectionFactory.newConnection(addresses);

        //3 通过connection创建一个Channel
        final Channel channel = connection.createChannel();
        // 创建一个type="direct"、持久化的、非自动删除的交换器
        channel.exchangeDeclare(EXCHANGE_NAME, "direct", true, false, null);
        //4 声明（创建）一个队列 (姓名 持久化 独占(顺序消费) 队列脱离exchange自动删除)
        channel.queueDeclare(QUEUE_NAME, true, false, false, null);

        // 将交换器和队列通过路由绑定
        channel.queueBind(QUEUE_NAME, EXCHANGE_NAME, ROUTING_KEY);

        channel.basicQos(64);   // 设置客户端最多接受未被ack的消息的个数
        //5 创建消费者
        Consumer consumer = new DefaultConsumer(channel) {
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                super.handleDelivery(consumerTag, envelope, properties, body);
                System.out.println("receive message: " + new String(body));
                try {
                    TimeUnit.SECONDS.sleep(1);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                try {
                    channel.basicAck(envelope.getDeliveryTag(), false);
                } catch (AlreadyClosedException ignore) {
                    try {
                        if (channel != null) {
                            channel.close();
                        }
                    } catch (TimeoutException e) {
                        e.printStackTrace();
                    }
                    connection.close();
                }

            }
        };

        channel.basicConsume(QUEUE_NAME, consumer);
        // 等待回调函数执行完毕后，关闭资源
        TimeUnit.SECONDS.sleep(5);
        channel.close();
        connection.close();
    }
}
